<?php
declare(strict_types=1);

/**
 * @Author:     Frank
 * @contact     frank_hhm@163.com
 * @Date:       2022-11-05 14:37:13
 * @Last Modified time: 2023-02-04 14:57:05
 */
namespace frank\base;

use think\facade\App;
use think\facade\Config;
use think\facade\Lang;
use frank\services\ValidateService;
use frank\constants\StatusCode;
use think\Response;
use think\exception\HttpResponseException;
use frank\services\NodeService;
use frank\utils\helper\StringHelper;
use frank\exception\CommonException;

/**
 * 控制器基础类
 */
abstract class BaseController extends \stdClass
{
    /**
     * Request实例
     * @var \app\Request
     */
    protected $request;

    /**
     * 应用实例
     * @var \think\App
     */
    protected $app;

    /**
     * 默认响应输出类型,支持json/xml/jsonp
     * @var string
     */
    protected $responseType = 'json';

    /**
     * 构造方法
     * @access public
     * @param App $app 应用对象
     */
    public function __construct(App $app)
    {
        $this->app = $app;
        $this->request = app('request');
        $this->initialize(); 
    }

    // 初始化
    protected function initialize()
    {
    }

    protected function checkAuth($roles = -1){
        $node = NodeService::instance()->getCurrent();
        $annotate = $this->request->annotate();
        $noAuth = $annotate['noAuth'][0] ?? false;
        $noAuth = !StringHelper::isTrue($noAuth);
        if($roles != -1 && $noAuth && !in_array($node,$roles)){
            throw new CommonException('暂无api接口权限！',702);
        }
    }

    /**
     * 快捷输入并验证（ 支持 规则 # 别名 ）
     * @param array $rules 验证规则（ 验证信息数组 ）
     * @param string $type 输入方式 ( post. 或 get. )
     * @return array
     */
    protected function _vali(array $rules, $type = '',$echoType='')
    {
        return ValidateService::instance()->init($rules, $type,$echoType);
    }
    

    /**
     * 操作成功
     * @param string      $message     提示消息
     * @param mixed       $data    返回数据
     */
    protected function success( $message = '', $data = null, $code =  StatusCode::SUCCESS)
    {
        if (is_array($message)) {
            $data = $message;
            $message = 'ok';
        }
        $this->result($message, $data, $code);
    }

    /**
     * 操作失败
     * @param string      $message     提示消息
     * @param mixed       $data    返回数据
     */
    protected function error( $message = '', $data = null, $code =  StatusCode::ERROR)
    {
        $this->result($message, $data, $code);
    }

    /**
     * 返回 API 数据
     * @param string      $message     提示消息
     * @param mixed       $data    返回数据
     * @param int         $code    错误码
     */
    public function result(string $message, $data = null,$code = [])
    {
        $result = [
            'code' => $code[0] ?? $code,
            'message'  => $message,
            'time' => $this->request->server('REQUEST_TIME'),
            'data' => $data,
        ];
        if ($result['message'] && !is_numeric($result['message'])) {
            if (!$range = $this->request->get('lang')) {
                $range = $this->request->cookie(Config::get('lang.cookie_var'));
            }
            $langData = array_values(Config::get('lang.accept_language', []));
            if (!in_array($range, $langData)) {
                $range = 'zh-cn';
            }
            $result['message'] = Lang::get($result['message'], [], $range);
        }
        // $response = Response::create($result,$this->responseType, 200)->header([])->options([]);
        // dump($response);die;
        throw new HttpResponseException(json($result));
    }
}
